package com.itheima.app.controller;

import com.itheima.domain.db.User;
import com.itheima.app.usermanager.UserManager;
import com.itheima.domain.db.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserManager userManager;
    //保存用户
    @PostMapping("user/save")
    public Long sava(@RequestBody User user){
        return userManager.save(user);
    }

    @GetMapping("user/findByPhone")
    public ResponseEntity findByPhone(String phone){
    return ResponseEntity.ok(userManager.findByPhone(phone));
    }
    @PostMapping("/user/login")
    public void sendSms(@RequestBody Map<String, String> param) {
        // 获取手机号
        String phone = param.get("phone");
        // 调用manager
        userManager.sendSms(phone);
    }
    @PostMapping("user/loginVerification")
    public ResponseEntity loginAndRegister(@RequestBody Map<String,String> param){
        // 1.接收请求参数
        String phone = param.get("phone");String verificationCode = param.get("verificationCode");
        // 2.调用manager
        return userManager.loginAndRegister(phone,verificationCode);

    }
    //用户信息完善
    @PostMapping("/user/loginReginfo")
    public  void  saveUser(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token){
        userManager.saveUser(userInfo,token);

    }
    //头像上传
    @PostMapping("/user/loginReginfo/head")
    public ResponseEntity headinsert(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
        return userManager.update(headPhoto,token);
    }
    @GetMapping("/users")
    public ResponseEntity findUserInfoVo(Long userID,Long huanxinID, @RequestHeader("Authorization") String token){

        if (userID!=null) {
            return userManager.findUserInfoVo(userID);
        }else if(huanxinID!=null){
            return userManager.findUserInfoVo(huanxinID);
        }else{
            User user = userManager.findUserByToken(token);
            return userManager.findUserInfoVo(user.getId());
        }
    }
    @PutMapping("users")
    public void updateUserInfoBase(@RequestBody UserInfo userInfo, @RequestHeader("Authorization") String token){
        // 调用manager
        userManager.updateUserInfoBase(userInfo,token);
    }
    @PostMapping("/users/header")
    public ResponseEntity updatehead(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
        return userManager.update(headPhoto,token);

    }
}